<template>
	<a-modal v-bind="options" class="bill-detail-dialog">
		<a-tabs v-model:activeKey="activeKey" type="card" class="dialog-card-container">
			<a-tab-pane key="info" tab="账单信息">
				<a-skeleton :loading="loadings.detail" active :paragraph="{rows: 15}">
					<a-descriptions title="客户信息" class="ant-descriptions-blockquote">
						<a-descriptions-item label="客户姓名">{{ detail.payerName }}</a-descriptions-item>
						<a-descriptions-item label="客户电话" :span="2">{{ detail.payerPhone }}</a-descriptions-item>
						<a-descriptions-item label="房源地址">{{ detail.fullHouseAddress }}</a-descriptions-item>
					</a-descriptions>
					<a-descriptions title="账单收支信息" class="ant-descriptions-blockquote ant-descriptions-inlineflex">
						<template #extra v-if="detail.spiltBillTopId">
							<a @click="visibles.split = true">关联账单(拆分)</a>
						</template>
						<a-descriptions-item label="账单摘要">{{ detail.billName }}</a-descriptions-item>
						<a-descriptions-item label="账单周期">
							{{ formatDate(detail.beginTime) }} 至 {{ formatDate(detail.endTime) }}
						</a-descriptions-item>
						<a-descriptions-item label="创建时间">{{ detail.createTime }}</a-descriptions-item>
						<a-descriptions-item :label="'应' + paymentStatus + '日期'">
							{{ formatDate(detail.predictTime) }}
						</a-descriptions-item>
						<a-descriptions-item label="完成时间">{{ detail.finishTime }}</a-descriptions-item>
						<a-descriptions-item label="账单类型">{{ billTypeMap[detail.billType] }}</a-descriptions-item>
						<a-descriptions-item :label="'待' + paymentStatus + '金额'">{{ detail.notOccurredMoney }}</a-descriptions-item>
						<a-descriptions-item :label="'已' + paymentStatus + '金额'" :span="2">
							{{ detail.occurredMoney }}
						</a-descriptions-item>
						<a-descriptions-item label="账单备注" :span="3">{{ detail.comment }}</a-descriptions-item>
						<a-descriptions-item label="账单附件" :span="3">
							<file-upload :biz-id="id" only-show-preview />
						</a-descriptions-item>
					</a-descriptions>
					<template v-if="detail.billStatus === 9">
						<a-descriptions title="作废信息" class="ant-descriptions-blockquote">
							<a-descriptions-item label="作废人">{{ detail.abandonName }}</a-descriptions-item>
							<a-descriptions-item label="作废时间">{{ detail.abandonDate }}</a-descriptions-item>
							<a-descriptions-item label="作废原因">{{ detail.abandonReason }}</a-descriptions-item>
						</a-descriptions>
					</template>
				</a-skeleton>
			</a-tab-pane>
			<a-tab-pane key="detail" tab="账单明细">
				<vxe-grid :data="detail.billDetailList" v-bind="gridOptions">
					<template #feeDirection="{row}">
						<a-tag color="blue" v-if="row.feeDirection === 1">收入</a-tag>
						<a-tag color="red" v-else>支出</a-tag>
					</template>
				</vxe-grid>
			</a-tab-pane>
			<a-tab-pane key="flow" tab="账单流水">
				<template v-if="detail.billFlowList && detail.billFlowList.length">
					<template v-for="(v, index) in detail.billFlowList" :key="index">
						<a-divider v-if="index !== 0" />
						<a-steps :current="-1" direction="vertical" disabled>
							<a-step>
								<template #icon>
									<svg-icon style="width: 32px; height: 32px" icon-class="launch" />
								</template>
								<template #description>
									<a-descriptions layout="vertical" bordered size="small">
										<a-descriptions-item label="发起">
											<a-row :gutter="[8, 8]">
												<a-col :span="8">
													<span class="label">金额：</span>
													{{ v.totalMoney.toLocaleString() }} 元（{{ v.paymentMethodValue }}）
												</a-col>
												<a-col :span="8">
													<span class="label">客户账号：</span>
													{{ v.paymentAccount }}
												</a-col>
												<a-col :span="8">
													<span class="label">支付时间：</span>
													{{ v.practicalTime }}
												</a-col>
												<a-col :span="8">
													<span class="label">摘要：</span>
													{{ (v.billFlowDetailList || []).map(o => o.feeSubject).join('/') }}
												</a-col>
												<a-col :span="8">
													<span class="label">经办人：</span>
													{{ v.affirmEmpName }}
												</a-col>
												<a-col :span="8">
													<span class="label">提交时间：</span>
													{{ v.createTime }}
												</a-col>
												<a-col :span="24">
													<span class="label">支付备注：</span>
													{{ v.comment }}
												</a-col>
											</a-row>
										</a-descriptions-item>
									</a-descriptions>
								</template>
							</a-step>
							<a-step>
								<template #icon>
									<svg-icon style="width: 32px; height: 32px" icon-class="approval" />
								</template>
								<template #description>
									<a-descriptions layout="vertical" bordered size="small">
										<a-descriptions-item label="审核">
											<a-row style="line-height: 30px">
												<a-col :span="8">
													<span class="label">审核状态：</span>
													<a-tag v-if="v.auditStatus" :color="statusMap[v.auditStatus || 1].color">
														{{ statusMap[v.auditStatus || 1].label }}
													</a-tag>
													<a-tag v-else>已作废</a-tag>
												</a-col>
												<a-col :span="8">
													<span class="label">审核人：</span>
													{{ v.auditEmpName }}
												</a-col>
												<a-col :span="8">
													<span class="label">审核时间：</span>
													{{ v.auditTime }}
												</a-col>
												<a-col :span="8">
													<span class="label">审核意见：</span>
													{{ v.auditComment }}
												</a-col>
											</a-row>
										</a-descriptions-item>
									</a-descriptions>
								</template>
							</a-step>
							<!-- <a-step>
									<template #title>审核中</template>
								</a-step> -->
						</a-steps>
					</template>
				</template>
				<a-empty v-else class="house-empty" />
			</a-tab-pane>
		</a-tabs>
		<template #footer>
			<a-space v-if="activeKey === 'info'">
				<a-button
					v-if="![9].includes(detail.billStatus) && ![1, '1'].includes(props.approvalStatus as number)"
					v-action="['mk_finance_contract-bill_zf']"
					danger
					@click="visibles.invalid = true">
					作废
				</a-button>
				<a-button
					v-if="detail.bizType === 2 && detail.billStatus === 1 && detail.notOccurredMoney >= 0 && ![1, '1'].includes(props.approvalStatus as number)"
					@click="collection"
					v-action="['mk_finance_contract-bill_cs']">
					催收
				</a-button>
				<a-button
					v-if="![1, '1'].includes(props.approvalStatus as number) &&  ![2,9].includes(detail.billStatus)"
					@click="onSplitBill(detail)"
					v-action="['mk_finance_contract-bill_cf']">
					拆分
				</a-button>
				<a-button
					v-if="detail.billStatus === 1 && ![1, '1'].includes(props.approvalStatus as number)"
					@click="visibles.edit = true"
					v-action="['mk_finance_contract-bill_bj']">
					编辑
				</a-button>
				<a-button
					v-if="detail.billStatus === 1 && ![1, '1'].includes(props.approvalStatus as number)"
					type="primary"
					@click="visibles.handle = true"
					v-action="['mk_finance_contract-bill_handel']">
					处理
				</a-button>
				<a-button
					v-if="detail.billStatus === 9 && ![1, '1'].includes(props.approvalStatus as number)"
					danger
					@click="deleteBill"
					v-action="['mk_finance_contract-bill_sc']">
					删除
				</a-button>
			</a-space>
			<template v-else>
				<a-button type="primary" v-action="['mk_finance_bill_dy']" @click="print()">打印</a-button>
			</template>
		</template>
	</a-modal>
	<!-- 编辑 -->
	<bill-edit-dialog v-model:visible="visibles.edit" :id="id" @close="getBillDetail()" />
	<!-- 处理 -->
	<bill-handle-dialog v-model:visible="visibles.handle" :id="id" @close="getBillDetail()" />
	<!-- 作废 -->
	<batch-invalid-dialog v-model:visible="visibles.invalid" :bills="[detail]" @close="getBillDetail()" />
	<!-- 打印账单 -->
	<bill-print-dialog v-model:visible="visibles.print" :id="id" />
	<!-- 关联拆分账单 -->
	<bill-split-record v-model:visible="visibles.split" :spilt-bill-top-id="detail.spiltBillTopId" />
	<!-- 账单拆分 -->
	<bill-split-dialog v-model:visible="visibles.splitBill" :id="currentRow.id" @close="getBillDetail()" />
</template>

<script setup lang="ts">
	import {createVNode, reactive, ref, toRef, watchEffect} from 'vue'
	import {VxeGridProps} from 'vxe-table'
	import {financeBillDelete, getFinanceByBillId, urgeToPay} from '@/api/bill'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import {Img} from 'yuxin-base/src/types'
	import {message, Modal} from 'ant-design-vue'
	import {QuestionCircleOutlined} from '@ant-design/icons-vue'
	import {BillDeatil, billTypeMap} from '@/interface/bill'
	import FileUpload from '@/components/common/file-upload.vue'
	import BillHandleDialog from '@/components/finance/dialog/bill-handle-dialog.vue'
	import BatchInvalidDialog from '@/components/finance/dialog/batch-invalid-dialog.vue'
	import BillPrintDialog from '@/components/finance/dialog/bill-print-dialog.vue'
	import BillEditDialog from '@/components/finance/dialog/bill-edit-dialog.vue'
	import BillSplitRecord from '@/components/finance/dialog/bill-split-record.vue'
	import BillSplitDialog from '@/components/finance/dialog/bill-split-dialog.vue'
	import {statusMap} from 'yuxin-base/src/constant'

	const props = defineProps<{
		// 账单id
		id?: string
		visible: boolean
		approvalStatus?: string | number | null
	}>()

	const loadings = reactive({
		detail: false
	})

	const visibles = reactive({
		edit: false,
		handle: false,
		invalid: false,
		print: false,
		split: false,
		splitBill: false
	})
	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		width: 1200,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})
	const paymentStatus = ref('收')
	const detail = ref<BillDeatil>({})
	const gridOptions = reactive<VxeGridProps>({
		height: 'auto',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '收支类型',
				width: 100,
				align: 'center',
				slots: {
					default: 'feeDirection'
				}
			},
			// {
			// 	title: '账单描述',
			// 	width: 150,
			// 	align: 'center',
			// 	// slots: {
			// 	// 	default: 'billDesc'
			// 	// }
			// },
			{
				title: '费用科目/费用承担方',
				minWidth: 180,
				formatter({row}) {
					return row.feeSubjectValue + '：' + (row.attributionType === 1 ? '企业承担' : '个人承担')
				}
			},
			// {
			// 	title: '费用科目',
			// 	minWidth: 150,
			// 	formatter({row}) {
			// 		let attributionType = ''
			// 		if (row.attributionType) {
			// 			attributionType = '/' + (row.attributionType === 1 ? '企业承担' : '个人承担')
			// 		}
			// 		return row.feeSubjectValue + attributionType
			// 	}
			// },
			// {
			// 	field: 'feeSubjectValue',
			// 	title: '费用科目',
			// 	minWidth: 150
			// },
			{
				field: 'originalMoney',
				title: '应收(付)',
				minWidth: 150,
				align: 'right'
			},
			{
				field: 'occurredMoney',
				title: '已收(付)',
				minWidth: 150,
				align: 'right'
			},
			{
				field: 'notOccurredMoney',
				title: '待收(付)',
				minWidth: 150,
				align: 'right'
			},
			{
				title: '费用周期',
				minWidth: 350,
				formatter({row}) {
					return formatDate(row.beginTime) + ' 至 ' + formatDate(row.endTime)
				}
			}
		]
	})

	const activeKey = ref<string>('info')
	watchEffect(() => {
		if (props.visible && props.id) {
			activeKey.value = 'info'
			getBillDetail()
		}
	})

	const getBillDetail = () => {
		if (props.id) {
			loadings.detail = true
			getFinanceByBillId(props.id)
				.then(({data}) => {
					detail.value = data
					if (data.billStatus === 1) {
						paymentStatus.value = data.notOccurredMoney > 0 ? '收' : '支'
					} else if (data.billStatus === 2) {
						paymentStatus.value = data.totalMoney > 0 ? '收' : '支'
					} else if (data.billStatus === 9) {
						paymentStatus.value = data.totalMoney > 0 ? '收' : '支'
					}
				})
				.finally(() => (loadings.detail = false))
		}
	}

	const state = reactive({
		currentMenu: '',
		printBillShow: false
	})

	// 催收
	const collection = (row: any) => {
		Modal.confirm({
			title: '催收',
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			content: `确定要给租户【${detail.value.payerName}】发送催收短信吗？`,
			async onOk() {
				await urgeToPay([props.id as string])
				message.success('操作成功')
			}
		})
	}

	// 删除
	const deleteBill = () => {
		Modal.confirm({
			title: '删除',
			mask: true,
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			content: '确定要删除该笔账单吗？',
			async onOk() {
				await financeBillDelete(props.id as string)
				message.success('操作成功')
			}
		})
	}
	const currentRow = ref<any>({})
	// 拆分
	const onSplitBill = (row: any) => {
		currentRow.value = row
		visibles.splitBill = true
	}
	// 打印
	const print = () => {
		visibles.print = true
	}

	const onCancel = () => {
		emits('update:visible', false)
		setTimeout(() => emits('close'), 100)
	}
</script>

<style lang="less">
	.bill-detail-dialog {
		.ant-modal-body {
			padding: 0;
			height: 600px;
			overflow: auto;

			.label {
				color: @text-color-secondary;
			}
		}

		.ant-descriptions-inlineflex {
			.ant-descriptions-header {
				display: inline-flex;

				.ant-descriptions-extra {
					padding-left: 12px;
				}
			}
		}
	}
</style>
